<!-- This file has the html of the editing page and calls lots of functions and initiates stuff. A very central and important file! -->

<?php
	$lang_lib = $_LANG['edit'];
	
	if(isset($_GET['file'])) {			
		$file = $_GET['file'].".html";
		$tmpfile = "tmp/".rand(0,1000000).".html";

		// TODO: Implement a better solution!
		// Redirects the user to the index page if processing of the first file has failed
		if(!file_exists($_SESSION['processed'].$file)){
			echo "<script language='javascript'>";
			echo "alert('".$lang_lib['process_fail_file'].$_GET['file'].$lang_lib['process_fail']."');";
			echo "window.location='index.php'";
			echo "</script>";
		}
		// Opens the processed files.
		else{
			copy($_SESSION['processed'].$file, $tmpfile);
			$folderpath = $tmpfile;
	
	
			$file = fopen($folderpath, 'r');
			$haystack = fread($file, filesize($folderpath));
			fclose($file);
			$tobeappended = "";
			preg_match_all("/group='([^']*)/", $haystack, $m);
			$table = $m[1];
			$table = array_unique($table);
			$colorcode = 103;
			$coloriterator = 0;
			foreach($table as $t) {
			  $r = rand(0,255); $g = rand(0,255); $b = rand(0,255);
			  while(( $r + $g + $b )< 420) {
				$r=($r+rand(0,127)) % 150+80; $g =($g+rand(0,127))%150+80;$b= ($b+rand(0,127)) % 150+80;
		                          }
			  $tobeappended .= "[group=\"".$t."\"]{background:rgb(".$r.",".$g.",".$b.");}\n";
			  $colorcode += 35;
			  $coloriterator++;
			}
			echo '<style type="text/css">'.$tobeappended.'</style>';
		}
	}
?>
<script type="text/javascript">
	// This function loads the text into the edit-view.
	$(document).ready(function(){

	    		$("#textArea").load('<?php if(isset($_GET["file"])) { echo $tmpfile; } else { echo "uusiteksti.txt";} ?>');
                              jQuery.fn.replaceAttr = function(aName,rxString,repString){
                                      return this.each(function(){
                                                      jQuery(this).attr(aName,jQuery(this).attr(aName).replace(rxString,repString))
   	                                 });
    	                        }

			// Here the two buttons preview and confirm are assigned functionality.
			$('#doChanges').click(function(){
					$("#fileChanges").replaceAttr('action', 'PLACEHOLDER', "doChanges.php");
					$("#fileChanges").replaceAttr('action', 'validate.php', "doChanges.php");
					$("#fileChanges").submit();
			});
			$('#validate').click(function(){
					$("#fileChanges").replaceAttr('action', 'PLACEHOLDER', "validate.php");
					$("#fileChanges").replaceAttr('action', 'doChanges.php', "validate.php");
					$("#fileChanges").submit();
			});
			
	});
	
	
	
</script>

<script type="text/javascript" language="javascript">
	var i=0;

	// This function opens the file selected from the dropdown menu.
 	function changePage() {

	  	var x=document.getElementById("droppie").selectedIndex;
		var doc=document.getElementById("droppie").options[x].text;
		window.location.assign("./index.php?p=edit&file="+doc);
	}




	// This fuction adds a row of 4 cells to the table!
	function addRow(tableID) { 
		    var table = document.getElementById(tableID);
       		var rowCount = table.rows.length;
		    var row = table.insertRow(rowCount);
	 
		    var cell1 = row.insertCell(0);
		    var element1 = document.createElement("input");
		    element1.type = "text";
		    element1.width = 60;
			
		    element1.setAttribute("name", "new_entry" + i);
		    cell1.appendChild(element1);
	 
		    var cell2 = row.insertCell(1);
		    
		    var cell4 = row.insertCell(2);
		    var element4 = document.createElement('a');
		    element4.setAttribute('class', 'small_button');
		    element4.setAttribute('href', 'javascript:void()');
		    element4.innerHTML = <?echo $lang_lib['delete_entry']?>;
		    element4.setAttribute('onclick', 'removeRow(this.parentNode.parentNode)');
		    cell4.appendChild(element4);
		    i++;
	}

	// This function removes a created row from the table.
	function removeRow(row){
		var parent = row.parentNode;
		parent.removeChild(row);
		
	}

    		
	// This function changes the background and the class of the row in the table. This is done so that our filter list can find out which words NOT to anonymize.
    function filter (x) {
		if (x.bgColor.toLowerCase() == '#e77471')	{
			x.setAttribute("bgColor", "#ffffff");
			x.setAttribute("class", "filter");
			x.childNodes[1].setAttribute("value", "ignore");			
			x.childNodes[7].childNodes[0].innerHTML = "<?=$lang_lib['change']?>";
		}
		else {
			x.setAttribute("bgColor", "#e77471");
			x.setAttribute("class", "NULL");
			x.childNodes[1].setAttribute("value", "delete");
			x.childNodes[7].childNodes[0].innerHTML = "<?=$lang_lib['nochange']?>";
		}
	}
</script>
<div class="column_set">
  <div class="column">
    <div id="text_container" class="document">
	    <!-- This form is a dropdown list with all the processed files in it. You switch between the files here. -->
	    <form action="Foob">
	    <select id="droppie" onchange="changePage()">
		<?php
			$dir = $_SESSION['uploads'];
			$dir2 = $_SESSION['processed'];
			$list = scandir("$dir");

			for ( $i = 1; $i <= count($list); $i += 1) {
				$filename = $list[$i];
				if(file_exists($dir2.$filename.".html")) {
					if ($filename == $_GET['file']) {
						$choice = 1;
					}
					else {
						$choice = 0;
					}
					$print_line = ' <option ';
					 if ($choice) {
						$print_line .= 'selected="selected"';
					}
					$print_line .= '>'. $filename . '</option>' . "\n";
					echo $print_line;
				}
			}

		?> 
	    </select>
	    </form>
	    <div id="textArea"></div>
    </div>
  </div>
  
  <div class="column">
		<div id="controls">
			<div class="blue_header"><legend><?echo $lang_lib['personInfo']?></legend></div>
			<div id="main_controls"> <!-- Controls may feature multiple types of subwindows in the future, for example the original document -->
				
					<!-- This is the word table in edit view. -->
					<div id="wordTable">
						<form id="fileChanges" method="post" name="fileChanges" action="PLACEHOLDER">
						<input type="hidden" name="filename" value="<?=$_GET['file']?>" />
						<table id="personInfo" class="tablesorter" width="100%" cellspacing="0" cellpadding="0" border="1">
							<thead>
								<tr>
								<th width="40%" class="header first"><?echo $lang_lib['name']?></th>
								<th width="40%" class="header"><?echo $lang_lib['replace']?></th>
								<th width="10%" class="header last"></th>
								</tr>
							</thead>
							<tbody id="gpnode">				
								<?php
								$f = file($_SESSION['processed'].$_GET['file'].".html.modified");
								$i = 0;
								$existing_groups = ""; // Holder for group names to identify unique entries in the site's variablelist.

								/* For each loop checks if the group has already been appended to the variable list. If not,
								then it generates the html code to append it. */

								foreach($f as $r) { 
									$r = explode(",", $r);
									if(sizeof($r) < 2) { print '<input type="hidden" name="level" value="'.$r[0].'" />'; continue; }
									if($r[0] == "modified") {
									 $size = sizeof($r);
									 $temporary_group = explode(" ", $existing_groups);
									 if(in_array($r[$size - 1], $temporary_group) == false){
							 			$existing_groups .= $r[$size - 1]." ";
						 		 		?>
										<tr bgcolor="#e77471">
										<input type="hidden" name="<?=$r[2]?>" value="none" />
										<td group="<?=trim($r[5])?>" id="<? echo trim($r[5])."cell";?>"><a style="display: block;" href="#<?=$r[4]?>"><?=$r[2]?></a></td>
										<td name="<?=$r[4]?>"> <?=$r[1]?> </td>
										<td><a class="small_button" href="javascript:void()" class="inputField" onclick='filter(this.parentNode.parentNode)'><?echo $lang_lib['nochange']?></a></td>
										</tr>
										<?php
									}
									} else {
										$size = sizeof($r);
											$temporary_group = explode(" ", $existing_groups);
											if(in_array($r[$size - 1], $temporary_group) == false){
										        $existing_groups .= $r[$size - 1]." ";
										        ?>
										        <tr>
										        <input type="hidden" name="<?=$r[1]?>" value="ignore" />
												<td group="<?=trim($r[5])?>" id="<? echo trim($r[5])."cell";?>"><a style="display: block;" href="#<?=$r[4]?>"><?=$r[1]?></a></td>
										        <td>Henkilö X</td>
										        <td><a class="small_button" href="javascript:void()" class="inputField" onclick='filter(this.parentNode.parentNode)'><?echo $lang_lib['change']?></a></td>
										        </tr>
										        <?php
											}
									}
								}
								?>
							</tbody>
						</table>
						</form>
					</div>
					
			</div>
					<!-- The buttons below the word table -->
					<div id="buttonDiv" class="column_set2">
					  <div class="column2">
						  <a class="small_button" href="javascript:void()" onclick="addRow('personInfo')"><?echo $lang_lib['addRow']?></a>
						</div>
						<div class="column2">
						  <a class="small_button" href="javascript:void()" id="doChanges"><?echo $lang_lib['preview']?></a>
						</div>
						<div class="column2">
						  <a class="small_button" href="javascript:void()" id="validate" onclick="validate()"><?echo $lang_lib['confirm']?></a>
						</div>
					</div>
			
		</div>
  </div>
  
</div>

					

